package com.jcfk.eam.service.mould;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.core.exception.CustomException;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.core.utils.IdUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.api.MdmServiceFegin;
import com.jcfk.eam.domain.dto.base.EamSopItemDTO;
import com.jcfk.eam.domain.dto.base.EamSopItemImgDTO;
import com.jcfk.eam.domain.dto.base.EamSopItemValueDTO;
import com.jcfk.eam.domain.dto.main.*;
import com.jcfk.eam.domain.dto.mould.*;
import com.jcfk.eam.domain.po.main.EamAssetInfo;
import com.jcfk.eam.domain.po.main.EamPointCheckDetail;
import com.jcfk.eam.domain.po.main.EamPointCheckDetailImg;
import com.jcfk.eam.domain.po.main.EamPointCheckOrder;
import com.jcfk.eam.domain.po.mould.EamMouldOutinboundRecord;
import com.jcfk.eam.domain.po.mould.MouldBomGroup;
import com.jcfk.eam.domain.po.mould.MouldGroupDetail;
import com.jcfk.eam.domain.po.mould.ProjectMould;
import com.jcfk.eam.domain.query.base.EamSopItemImgQuery;
import com.jcfk.eam.domain.query.mould.ProjectMouldQuery;
import com.jcfk.eam.enums.AssetKind;
import com.jcfk.eam.service.base.EamSopItemImgService;
import com.jcfk.eam.service.base.EamSopStandardService;
import com.jcfk.eam.service.main.EamAssetInfoService;
import com.jcfk.eam.service.main.EamPointCheckDetailImgService;
import com.jcfk.eam.service.main.EamPointCheckDetailService;
import com.jcfk.eam.service.main.EamPointCheckOrderService;
import com.jcfk.system.api.utils.CodeBuildUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 模具台账管理
 */
@Service
public class MouldAssetInfoService {
    @Autowired
    private EamAssetInfoService eamAssetInfoService;

    @Autowired
    private MdmServiceFegin mdmServiceFegin;

    @Autowired
    private EamPointCheckOrderService eamPointCheckOrderService;

    @Autowired
    private MouldWorkRecordService mouldWorkRecordService;

    @Autowired
    private EamMouldProjectMouldService eamMouldProjectMouldService;

    @Autowired
    private MouldGroupDetailService mouldGroupDetailService;


    @Autowired
    private MouldGroupRecordService mouldGroupRecordService;

    @Autowired
    private MouldGroupDetailService detailService;

    @Autowired
    private EamPointCheckDetailService eamPointCheckDetailService;

    @Autowired
    private EamPointCheckDetailImgService eamPointCheckDetailImgService;

    @Autowired
    private MouldBomGroupService mouldBomGroupService;

    @Autowired
    private EamSopStandardService eamSopStandardService;

    @Autowired
    private EamMouldTaskInfoDetailService eamMouldTaskInfoDetailService;

    @Autowired
    private EamMouldOutinboundRecordService eamMouldOutinboundRecordService;
    @Autowired
    private EamSopItemImgService eamSopItemImgService;


    @Transactional(rollbackFor = Exception.class)
    public RetResult<?> inStock(MouldLedgerOperateDTO dto) {
        // 台账入库/操作记录
        if (dto.getEamAssetInfo() == null) {
            EamAssetInfo eamAssetInfo = new EamAssetInfo();
            eamAssetInfo.setAssetKind(AssetKind.MOULD.getValue());
            eamAssetInfo.setAssetCode(dto.getCode());
            eamAssetInfo.setAssetName(dto.getMdmMaterialDTO().getMaterialName());
//            eamAssetInfo.setMaterialCode(dto.getMdmMaterialDTO().getMaterialCode());
//            eamAssetInfo.setMaterialName(dto.getMdmMaterialDTO().getMaterialName());
//            eamAssetInfo.setMaterialId(dto.getMdmMaterialDTO().getId());
            eamAssetInfo.setAssetStatus(3);
//            eamAssetInfo.setStorageStatus(1);
            eamAssetInfo.setAccountDate(new Date());
            eamAssetInfo.setArrivalDate(new Date());
//            eamAssetInfo.setProcessCode(dto.getProcessCode());
//            eamAssetInfo.setProjectCode(dto.getProjectCode());
            eamAssetInfo.setCheckPerson(SecurityUtils.getUserId());

            eamAssetInfo.setAssetTypeId("dcabbfe2b2df445f81f1bb14867cd173");
            eamAssetInfo.setAssetTypeCode("TEST1");
            eamAssetInfo.setAssetTypeName("测试模具1");
            eamAssetInfoService.setDefaultValue(eamAssetInfo);
            eamAssetInfoService.save(eamAssetInfo);

            dto.setEamAssetInfo(eamAssetInfo);

            mouldWorkRecordService.insertWork(dto, "1");
        }

        // 保存尺寸点检信息
        if (dto.getEamSopStandardDTO() != null)
            this.saveCheckOrder(dto.getEamAssetInfo(), dto.getEamSopStandardDTO(), 1);

        return RetResult.ok();
    }

    /**
     * 保存检验点检单结果
     *
     * @param eamAssetInfo
     * @param eamSopStandardDTO
     * @param orderStatus
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveCheckOrder(EamAssetInfo eamAssetInfo, EamPointCheckResultDTO eamSopStandardDTO, Integer orderStatus) {
        // 保存尺寸点检信息
        EamPointCheckOrder eamPointCheckOrder = new EamPointCheckOrder();
        eamPointCheckOrder.setAssetKind(AssetKind.MOULD.getValue());
        eamPointCheckOrder.setOrderNo(CodeBuildUtils.buildCode("CheckOrderNo", "CheckOrderNo"));
        eamPointCheckOrder.setSopTypeId(eamSopStandardDTO.getSopTypeId());
        eamPointCheckOrder.setSopTypeCode(eamSopStandardDTO.getSopTypeCode());
        eamPointCheckOrder.setSopStandardId(eamSopStandardDTO.getId());
        eamPointCheckOrder.setSopStandardCode(eamSopStandardDTO.getStandardCode());
        eamPointCheckOrder.setAssetId(eamAssetInfo.getId());
        eamPointCheckOrder.setWorkTime(new Date());
        eamPointCheckOrder.setOrderStatus(orderStatus);
        eamPointCheckOrder.setAssetCode(eamAssetInfo.getAssetCode());
        eamPointCheckOrder.setAssetName(eamAssetInfo.getAssetName());
        if (orderStatus.equals(2)) {
            eamPointCheckOrder.setExecutePersonId(SecurityUtils.getUserId());
            eamPointCheckOrder.setExecutePersonName(SecurityUtils.getUserName());
        }
        eamPointCheckOrderService.setDefaultValue(eamPointCheckOrder);
        eamPointCheckOrderService.save(eamPointCheckOrder);

        List<EamPointCheckDetail> details = new ArrayList<>();
        List<EamPointCheckDetailImg> files = new ArrayList<>();
        Integer index = 1;
        for (EamSopItemDTO itemDTO : eamSopStandardDTO.getItemDTOS()) {
            EamPointCheckDetail detail = new EamPointCheckDetail();
            detail.setSeq(index);
            detail.setId(IdUtils.simpleUUID());
            detail.setOrderId(eamPointCheckOrder.getId());
            detail.setSopItemId(itemDTO.getId());
            detail.setSopItemName(itemDTO.getSopItemName());
            detail.setSopItemValue(itemDTO.getSaveValue());
            if (itemDTO.getStandardValue().equals("1")) {
                // 测量项
                detail.setSopItemValue(itemDTO.getSaveValue());
                if (!StrUtil.isEmpty(itemDTO.getStandardMinValue()) && !StrUtil.isEmpty(itemDTO.getStandardMaxValue())) {
                    if (itemDTO.getSaveValue() != null) {
                        Double itemValue = Double.valueOf(itemDTO.getSaveValue());
                        Double standardMinValue = Double.valueOf(itemDTO.getStandardMinValue());
                        Double standardMaxValue = Double.valueOf(itemDTO.getStandardMaxValue());
                        if (itemValue > standardMinValue && itemValue < standardMaxValue) {
                            detail.setSopItemResult("1");
                        } else {
                            detail.setSopItemResult("0");
                        }
                    }
                }
            } else {
                // 非测量项
                detail.setSopItemValueId(itemDTO.getSaveValue());
                for (int i = 0; i < itemDTO.getDetails().size(); i++) {
                    if (detail.getSopItemValue() != null && detail.getSopItemValue().equals(itemDTO.getDetails().get(i).getId())) {
                        EamSopItemValueDTO eamSopItemValueDTO = itemDTO.getDetails().get(i);
                        detail.setSopItemValue(eamSopItemValueDTO.getStandardValue());
                        detail.setSopItemResult(eamSopItemValueDTO.getResultValue());
                    }

                }
            }
            eamPointCheckDetailService.setDefaultValue(detail);
            details.add(detail);
            for (EamSopItemImgDTO image : itemDTO.getImages()) {
                EamPointCheckDetailImg eamPointCheckDetailImg = new EamPointCheckDetailImg();
                eamPointCheckDetailImg.setPointCheckDetailId(detail.getId());
                eamPointCheckDetailImg.setUrl(image.getUrl());
                eamPointCheckDetailImg.setFileType(image.getFileType());
                eamPointCheckDetailImg.setFilename(image.getFilename());
                eamPointCheckDetailImg.setOriginalfilename(image.getOriginalfilename());
                eamPointCheckDetailImg.setPath(image.getPath());
                eamPointCheckDetailImgService.setDefaultValue(eamPointCheckDetailImg);
                files.add(eamPointCheckDetailImg);
            }

            index++;
        }

        if (details.size() > 0) eamPointCheckDetailService.saveBatch(details);
        if (files.size() > 0) eamPointCheckDetailImgService.saveBatch(files);
    }

    @Transactional(rollbackFor = Exception.class)
    public RetResult<?> outStock(MouldLedgerOperateDTO dto) {
        EamAssetInfo eamAssetInfo = eamAssetInfoService.getById(dto.getEamAssetInfo().getId());

        if (eamAssetInfo == null) {
            throw new CustomException("模具记录不能为空!");
        }

        // if (eamAssetInfo.getAssetStatus() != 3) {
        //     throw new CustomException("该模具不是处于空闲状态，不能操作!");
        // }

        if (eamAssetInfo.getAssetStatus() == 1) {
            throw new CustomException("该工装已经到生产库，无需再操作!");
        }
//
        eamAssetInfo.setAssetStatus(1);
//        eamAssetInfo.setStorageStatus(2);
        eamAssetInfoService.setDefaultValue(eamAssetInfo);
        eamAssetInfoService.updateById(eamAssetInfo);


        mouldWorkRecordService.insertWork(dto, "2");
        return RetResult.ok();
    }


    /**
     * 通用模具台账管理
     * 根据id 查询详情
     */
    public MouldLedgerOperateDTO getProjectMouldlist(String code) {
        MouldLedgerOperateDTO dto = new MouldLedgerOperateDTO();
        String sapCode = code.substring(0, 7);
        dto.setSapCode(sapCode);
        String projectCode = code.substring(7, 11);
        dto.setProjectCode(projectCode);
        String dataString = code.substring(11, 19);
        dto.setDataString(dataString);
        String processCode = code.substring(code.length() - 3);
        dto.setProcessCode(processCode);
        dto.setCode(code);

        RetResult<MdmMaterialDTO> mdmMaterialDTORetResult = mdmServiceFegin.getMdmmaterial(sapCode);
        dto.setMdmMaterialDTO(mdmMaterialDTORetResult.getData());


        QueryWrapper<ProjectMould> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ProjectMould::getMaterialCode, sapCode);


        MouldGroupRecordDTO groupRecordDTO = mouldGroupRecordService.getGroupRecordBySubMoulds(code);

        if (groupRecordDTO == null) {
            // throw new CustomException("根据该模具编码未检索到模具模具组合记录!");
            return dto;
        }

        QueryWrapper<MouldBomGroup> bomGroupQueryWrapper = new QueryWrapper<>();
        bomGroupQueryWrapper.lambda().eq(MouldBomGroup::getBomCode, groupRecordDTO.getBomCode());
        MouldBomGroup mouldBomGroup = mouldBomGroupService.getOne(bomGroupQueryWrapper);

        if (mouldBomGroup == null) {
            // throw new CustomException("根据该模具编码未检索bom组合关系!");
            return dto;
        }

        ProjectMouldQuery query = new ProjectMouldQuery();
        query.setEquipId(mouldBomGroup.getEquipId());
        query.setMaterialCode(sapCode);
        List<ProjectMouldDTO> modProjectMoulds = eamMouldProjectMouldService.getList(query);
        if (modProjectMoulds.size() <= 0) {
            // throw new CustomException("根据该模具编码未检索到产品模具关系!");
            return dto;
        }
        dto.setMouldDTOS(modProjectMoulds);

        groupRecordDTO.getBomCode();

        return dto;
    }


    /**
     * 通用模具台账管理
     * 根据id 查询详情
     */
    public void installMod(@RequestBody MouldLedgerOperateDTO dto) {
        EamAssetInfo eamAssetInfo = eamAssetInfoService.getById(dto.getEamAssetInfo().getId());

        if (eamAssetInfo == null) {
            throw new CustomException("根据该模具编码未检索到模具记录!");
        }

        // if (eamAssetInfo.getAssetStatus() != 3) {
        //     throw new CustomException("该模具不是处于空闲状态，不能操作!");
        // }

//        if (eamAssetInfo.getStorageStatus() == 3) {
//            throw new CustomException("该工装已经到设备，无需再操作!");
//        }

        eamAssetInfo.setAssetStatus(1);
//        eamAssetInfo.setStorageStatus(3);
//        eamAssetInfo.setProjectId(dto.getProjectMouldDTO().getProjectId());
//        eamAssetInfo.setProcessId(dto.getProjectMouldDTO().getProcessId());
//        eamAssetInfo.setProcessCode(dto.getProjectMouldDTO().getProcessCode());
//        eamAssetInfo.setProjectCode(dto.getProjectMouldDTO().getProjectCode());
//
//        eamAssetInfo.setEquipId(dto.getProjectMouldDTO().getEquipId());
//        eamAssetInfo.setEquipCode(dto.getProjectMouldDTO().getEquipCode());

        eamAssetInfoService.setDefaultValue(eamAssetInfo);
        eamAssetInfoService.updateById(eamAssetInfo);

        MouldGroupDetail detail = new MouldGroupDetail();
        detail.setMouldStatus("1");
        QueryWrapper<MouldGroupDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MouldGroupDetail::getMouldCode, dto.getCode());
        mouldGroupDetailService.update(detail, queryWrapper);

        mouldWorkRecordService.insertWork(dto, "5");
    }


    /**
     * 通用模具台账管理
     * 根据id 查询详情
     */
    public MouldLedgerOperateDTO getStripList(String code) {

        MouldLedgerOperateDTO dto = new MouldLedgerOperateDTO();
        String sapCode = code.substring(0, 7);
        dto.setSapCode(sapCode);
        String projectCode = code.substring(7, 11);
        dto.setProjectCode(projectCode);
        String dataString = code.substring(11, 19);
        dto.setDataString(dataString);
        String processCode = code.substring(code.length() - 3);
        dto.setProcessCode(processCode);
        dto.setCode(code);

        RetResult<MdmMaterialDTO> mdmMaterialDTORetResult = mdmServiceFegin.getMdmmaterial(sapCode);
        dto.setMdmMaterialDTO(mdmMaterialDTORetResult.getData());


        QueryWrapper<EamAssetInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamAssetInfo::getAssetCode, code);
        EamAssetInfo eamAssetInfo = eamAssetInfoService.getOne(queryWrapper);
        if (eamAssetInfo == null) {
            throw new CustomException("根据该模具编码未检索到模具记录!");
        }

        if (eamAssetInfo.getAssetStatus() == 8) {
            throw new CustomException("该模具状态已经是待维护，无需再操作!");
        }

        dto.setEamAssetInfo(eamAssetInfo);

        // MouldGroupRecordDTO groupRecordDTO = mouldGroupRecordService.getGroupRecordBySubMoulds(code);
        //
        // if (groupRecordDTO == null) {
        //     throw new CustomException("根据该模具编码未检索到模具模具组合记录!");
        // }
        // dto.setModGroupRecordDTO(groupRecordDTO);
        //
        // MouldAssemblyTableDto mouldAssemblyTableDto = mouldGroupRecordService.getListByMouldCodeAndBomCode(groupRecordDTO.getMouldCode(), groupRecordDTO.getBomCode());
        //
        // if (mouldAssemblyTableDto == null) {
        //     throw new CustomException("根据该模具编码未检索到模具模具组合记录!");
        // }
        // dto.setMouldAssemblyTableDto(mouldAssemblyTableDto);

        return dto;
    }

    public void strip(MouldLedgerOperateDTO dto) {

        EamAssetInfo eamAssetInfo = eamAssetInfoService.getById(dto.getEamAssetInfo().getId());

        if (eamAssetInfo == null) {
            throw new CustomException("模具记录不能为空!");
        }

        // if (eamAssetInfo.getAssetStatus() == 1) {
        //     throw new CustomException("该模具状态已经是待维护，无需再操作!");
        // }

//        eamAssetInfo.setStorageStatus(2);
        eamAssetInfo.setAssetStatus(1);
//        eamAssetInfo.setEquipCode("");
//        eamAssetInfo.setEquipId("");
        eamAssetInfoService.setDefaultValue(eamAssetInfo);
        eamAssetInfoService.updateById(eamAssetInfo);


        // MouldGroupRecord mouldGroupRecord = mouldGroupRecordService.getById(dto.getModGroupRecordDTO().getId());
        // mouldGroupRecord.setMouldStatus("1");
        // mouldGroupRecordService.setDefaultValue(mouldGroupRecord);
        // mouldGroupRecordService.updateById(mouldGroupRecord);

        // List<MouldGroupDetailDTO> assemblyDetailList = mouldGroupRecordService.getAssemblyDetailList(dto.getModGroupRecordDTO().getMouldCode(), dto.getModGroupRecordDTO().getBomCode());
        // List<String> ids = assemblyDetailList.stream().map(MouldGroupDetailDTO::getId).collect(Collectors.toList());
        //
        // if (ids.size() > 0) {
        //     QueryWrapper<MouldGroupDetail> queryWrapper = new QueryWrapper<>();
        //     queryWrapper.lambda().in(MouldGroupDetail::getId, ids);
        //     MouldGroupDetail detail = new MouldGroupDetail();
        //     detail.setMouldStatus("8");
        //     detailService.update(detail, queryWrapper);
        // }

        mouldWorkRecordService.insertWork(dto, "6");

    }

    /**
     * 获取点检信息
     */
    public EamMouldTaskInfoDetailDTO getSpotCheck(String sopTypeCode, EamMouldTaskInfoDetailDTO dto) {
//        List<EamPointCheckResultDTO> listCheckResult = getSopStandardByOrder(dto);
//        dto.setListCheckResult(listCheckResult);
//        List<EamPointCheckOrderDTO> listCheckOrder = getCheckOrder(dto, 2);

        //       if (listCheckOrder == null) {
        EamMouldTaskInfoDetailDTO detailDTO = eamMouldTaskInfoDetailService.get(dto.getId());
        EamAssetInfoDTO eamAssetInfoDTO = eamAssetInfoService.getInfobyMould(detailDTO.getMouldCode());
        dto.setMouldCode(detailDTO.getMouldCode());
        dto.setMouldName(detailDTO.getMouldName());
        dto.setMouldTypeName(eamAssetInfoDTO.getAssetTypeName());
        dto.setLocationName(eamAssetInfoDTO.getLocationName());
        dto.setLocationId(eamAssetInfoDTO.getLocationId());
        dto.setListCheckOrder(getSopStandardByOrder(sopTypeCode, dto));
//            return dto;
        //       }
        //       dto.setListCheckOrder(listCheckOrder);
        return dto;
    }

    /**
     * 获取点检信息
     */
    public EamAssetInfoDTO getSpotCheck(String sopTypeCode, EamAssetInfoDTO dto) {
//        List<EamPointCheckResultDTO> listCheckResult = getSopStandardByOrder(dto);
//        dto.setListCheckResult(listCheckResult);
//        List<EamPointCheckOrderDTO> listCheckOrder = getCheckOrder(dto, 2);

        //       if (listCheckOrder == null) {
        dto.setListCheckOrder(getSopStandardByOrder(sopTypeCode, dto));
//            return dto;
        //       }
        //       dto.setListCheckOrder(listCheckOrder);
        return dto;
    }

    /**
     * 通过点检项信息获取工单--入库
     */
    public List<EamPointCheckOrderDTO> getSopStandardByOrder(String sopTypeCode, EamAssetInfoDTO dto) {
        List<EamPointCheckOrderDTO> listCheckOrder = new ArrayList<>();
        QueryWrapper<EamMouldOutinboundRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamMouldOutinboundRecord::getDeleted, 0);
        queryWrapper.lambda().eq(EamMouldOutinboundRecord::getSubmitStatus, 0);
        queryWrapper.lambda().eq(EamMouldOutinboundRecord::getMouldCode, dto.getAssetCode());
        queryWrapper.lambda().eq(EamMouldOutinboundRecord::getOutinboundType, 1);
        queryWrapper.lambda().orderByDesc(EamMouldOutinboundRecord::getOutinboundTime);
        List<EamMouldOutinboundRecord> recordList = eamMouldOutinboundRecordService.list(queryWrapper);
        String planId = null;
        if (recordList.size() > 0) {
            EamMouldOutinboundRecord eamMouldOutinboundRecord = recordList.get(0);
            planId = eamMouldOutinboundRecord.getId();
        }
        EamPointCheckResultDTO dtoCheckResult = eamSopStandardService.getSopStandard(sopTypeCode, dto.getAssetTypeCode(), planId);
        if (dtoCheckResult != null) {
            listCheckOrder.add(getCheckOrder(dtoCheckResult, 1));
        }
        return listCheckOrder;
    }


    /**
     * 通过点检项信息获取工单--出库
     */
    public List<EamPointCheckOrderDTO> getSopStandardByOrder(String sopTypeCode, EamMouldTaskInfoDetailDTO dto) {
        List<EamPointCheckOrderDTO> listCheckOrder = new ArrayList<>();
        EamPointCheckResultDTO dtoCheckResult = eamSopStandardService.getSopStandard(sopTypeCode, dto.getMouldType(), dto.getId());
        if (dtoCheckResult != null) {
            listCheckOrder.add(getCheckOrder(dtoCheckResult, 1));
        }
        return listCheckOrder;
    }

    public EamPointCheckOrderDTO getCheckOrder(EamPointCheckResultDTO eamSopStandardDTO, Integer orderStatus) {
        // 保存尺寸点检信息
        EamPointCheckOrderDTO eamPointCheckOrder = new EamPointCheckOrderDTO();
        eamPointCheckOrder.setAssetKind(AssetKind.MOULD.getValue());
        //eamPointCheckOrder.setOrderNo(CodeBuildUtils.buildCode("CheckOrderNo", "CheckOrderNo"));
        eamPointCheckOrder.setSopTypeId(eamSopStandardDTO.getSopTypeId());
        eamPointCheckOrder.setSopTypeCode(eamSopStandardDTO.getSopTypeCode());
        eamPointCheckOrder.setSopStandardId(eamSopStandardDTO.getId());
        eamPointCheckOrder.setSopStandardCode(eamSopStandardDTO.getStandardCode());
        eamPointCheckOrder.setAssetId(eamSopStandardDTO.getId());
        eamPointCheckOrder.setWorkTime(new Date());
        eamPointCheckOrder.setOrderStatus(orderStatus);
        eamPointCheckOrder.setAssetCode(eamSopStandardDTO.getStandardCode());
        eamPointCheckOrder.setAssetName(eamSopStandardDTO.getStandardName());
        if (orderStatus.equals(2)) {
            eamPointCheckOrder.setExecutePersonId(SecurityUtils.getUserId());
            eamPointCheckOrder.setExecutePersonName(SecurityUtils.getUserName());
        }
        List<EamPointCheckDetailDTO> details = new ArrayList<>();
        Integer index = 1;
        for (EamSopItemDTO itemDTO : eamSopStandardDTO.getItemDTOS()) {
            EamPointCheckDetailDTO detail = new EamPointCheckDetailDTO();
            detail.setSeq(index);
            detail.setOrderId(eamPointCheckOrder.getId());
            detail.setSopItemId(itemDTO.getId());
            detail.setSopItemName(itemDTO.getSopItemName());
            detail.setSopItemValue(itemDTO.getSaveValue());
            detail.setSopItem(itemDTO);
            /**
             * 添加作业项图片
             */
            if (StrUtil.isNotEmpty(itemDTO.getId())) {
                EamSopItemImgQuery query = new EamSopItemImgQuery();
                query.setSopItemId(itemDTO.getId());
                List<EamSopItemImgDTO> eamSopItemImgDTOList = eamSopItemImgService.getList(query);
                detail.setItemImages(eamSopItemImgDTOList);
            }
            if (itemDTO.getStandardValue().equals("1")) {
                // 测量项
                detail.setSopItemValue(itemDTO.getSaveValue());
                if (!StrUtil.isEmpty(itemDTO.getStandardMinValue()) && !StrUtil.isEmpty(itemDTO.getStandardMaxValue())) {
                    if (StrUtil.isNotEmpty(itemDTO.getSaveValue())) {
                        Double itemValue = Double.valueOf(itemDTO.getSaveValue());
                        Double standardMinValue = Double.valueOf(itemDTO.getStandardMinValue());
                        Double standardMaxValue = Double.valueOf(itemDTO.getStandardMaxValue());
                        if ((itemValue > standardMinValue && itemValue < standardMaxValue) || standardMinValue.equals(itemValue) || standardMaxValue.equals(itemValue)) {
                            detail.setSopItemResult("1");
                        } else {
                            detail.setSopItemResult("0");
                        }
                    } else {
                        detail.setSopItemResult("1");
                    }
                }
            } else {
                // 非测量项
                // TODO: 2025/7/31 出库点检查询非测量
                detail.setSopItemValueId(itemDTO.getSaveValue());
                for (int i = 0; i < itemDTO.getDetails().size(); i++) {
                    EamSopItemValueDTO eamSopItemValueDTO = itemDTO.getDetails().get(i);
                    if (StrUtil.isNotBlank(itemDTO.getSaveValue())) {
                        // 赋值结果值
                        if (detail.getSopItemValueId() != null && detail.getSopItemValueId().equals(itemDTO.getDetails().get(i).getId())) {
                            eamSopItemValueDTO = itemDTO.getDetails().get(i);
                            detail.setSopItemValue(eamSopItemValueDTO.getStandardValue());
                            detail.setSopItemResult(eamSopItemValueDTO.getResultValue());
                        }
                    } else {
                        // 默认选中合格
                        if (eamSopItemValueDTO.getResultValue().equals("1")) {
                            detail.setSopItemValue(eamSopItemValueDTO.getStandardValue());
                            detail.setSopItemValueId(eamSopItemValueDTO.getId());
                            detail.setSopItemResult(eamSopItemValueDTO.getResultValue());
                        }
                    }
                }
            }
            details.add(detail);
        }
        eamPointCheckOrder.setDetails(details);
        return eamPointCheckOrder;
    }

    /**
     * 保存点检单
     *
     * @param eamPointCheckOrderDTO
     */
    public void saveSpotCheck(EamPointCheckOrderDTO eamPointCheckOrderDTO) {

        EamPointCheckOrder eamPointCheckOrder = new EamPointCheckOrder();
        BeanUtils.copyProperties(eamPointCheckOrderDTO, eamPointCheckOrder);

        // 保存尺寸点检信息
        eamPointCheckOrder.setAssetKind(AssetKind.MOULD.getValue());
        if ("ck".equals(eamPointCheckOrderDTO.getSopTypeCode())) {
            eamPointCheckOrder.setOrderNo(CodeBuildUtils.buildCode("CheckOrderNoOut", "CheckOrderNoOut"));
        }
        if ("rk".equals(eamPointCheckOrderDTO.getSopTypeCode())) {
            eamPointCheckOrder.setOrderNo(CodeBuildUtils.buildCode("CheckOrderNoInt", "CheckOrderNoInt"));
        }
//        eamPointCheckOrder.setSopTypeId(eamSopStandardDTO.getSopTypeId());
//        eamPointCheckOrder.setSopTypeCode(eamSopStandardDTO.getSopTypeCode());
//        eamPointCheckOrder.setSopStandardId(eamSopStandardDTO.getId());
//        eamPointCheckOrder.setSopStandardCode(eamSopStandardDTO.getStandardCode());
        eamPointCheckOrder.setAssetId(eamPointCheckOrderDTO.getAssetId());
        eamPointCheckOrder.setWorkTime(new Date());
        //eamPointCheckOrder.setOrderStatus(orderStatus);
        eamPointCheckOrder.setAssetCode(eamPointCheckOrderDTO.getAssetCode());
        eamPointCheckOrder.setAssetName(eamPointCheckOrderDTO.getAssetName());
        if (eamPointCheckOrder.getOrderStatus().equals(2)) {
            eamPointCheckOrder.setExecutePersonId(SecurityUtils.getUserId());
            eamPointCheckOrder.setExecutePersonName(SecurityUtils.getUserName());
        }
        long noPassCount = eamPointCheckOrderDTO.getDetails().stream().filter(p -> StrUtil.isNotEmpty(p.getSopItemResult()) && p.getSopItemResult().equals("0")).count();
        eamPointCheckOrder.setCheckResult(noPassCount > 0 ? 0 : 1);
        eamPointCheckOrderService.setDefaultValue(eamPointCheckOrder);
        eamPointCheckOrderService.saveOrUpdate(eamPointCheckOrder);


        List<String> detailIds = new ArrayList<>();
        List<EamPointCheckDetailImgDTO> images = new ArrayList<>();
        EamPointCheckOrderDTO saveDto = new EamPointCheckOrderDTO();
        List<EamPointCheckDetailDTO> saveDetails = new ArrayList<>();
        for (EamPointCheckDetailDTO detail : eamPointCheckOrderDTO.getDetails()) {
            if (detail.getSopItem().getStandardValue().equals("1")) {
                // 测量项
                EamPointCheckDetailDTO saveDetail = new EamPointCheckDetailDTO();
                if (!StrUtil.isEmpty(detail.getSopItem().getStandardMinValue()) && !StrUtil.isEmpty(detail.getSopItem().getStandardMaxValue())) {
                    if (StrUtil.isNotEmpty(detail.getSopItemValue())) {
                        Double itemValue = Double.valueOf(detail.getSopItemValue());
                        Double standardMinValue = Double.valueOf(detail.getSopItem().getStandardMinValue());
                        Double standardMaxValue = Double.valueOf(detail.getSopItem().getStandardMaxValue());
                        if ((itemValue > standardMinValue && itemValue < standardMaxValue) || standardMinValue.equals(itemValue) || standardMaxValue.equals(itemValue)) {
                            detail.setSopItemResult("1");
                        } else {
                            detail.setSopItemResult("0");
                        }
                    } else {
                        detail.setSopItemResult("1");
                    }
                }
                BeanUtils.copyProperties(detail, saveDetail);
                saveDetails.add(saveDetail);
            } else {
                // 非测量项
                // TODO: 2025/7/31 出库点检保存非测量
                for (int i = 0; i < detail.getSopItem().getDetails().size(); i++) {
                    EamPointCheckDetailDTO saveDetail = new EamPointCheckDetailDTO();
                    BeanUtils.copyProperties(detail, saveDetail);
                    if (detail.getSopItemValueId() != null && detail.getSopItemValueId().equals(detail.getSopItem().getDetails().get(i).getId())) {
                        EamSopItemValueDTO eamSopItemValueDTO = detail.getSopItem().getDetails().get(i);
                        saveDetail.setSopItemValue(eamSopItemValueDTO.getStandardValue());
                        saveDetail.setSopItemResult(eamSopItemValueDTO.getResultValue());
                        saveDetail.setSopItemValueId(eamSopItemValueDTO.getId());
                        saveDetails.add(saveDetail);
                    }
                }
            }
            saveDto.setDetails(saveDetails);
            detailIds.add(detail.getId());
            for (EamPointCheckDetailImgDTO imageDto : detail.getImages()) {
                imageDto.setPointCheckDetailId(detail.getId());
                images.add(imageDto);
            }
        }
        eamPointCheckOrderService.saveImg(saveDto, eamPointCheckOrder);
    }

    /**
     * 保存出库点检信息
     */
    public void saveSpotCheck(String sopTypeCode, EamMouldTaskInfoDetailDTO dto) {
        if (dto.getListCheckOrder() == null) {
            return;
        }
        // 保存点检详情数据
        EamMouldTaskInfoDetailDTO detailDTO = eamMouldTaskInfoDetailService.get(dto.getId());

        detailDTO.setPassStatus(dto.getPassStatus());
        detailDTO.setLastUpdatedUserId(SecurityUtils.getUserId());
        detailDTO.setLastUpdateTime(new Date());
        eamMouldTaskInfoDetailService.update(detailDTO);

        //删除旧的点检数据
        EamPointCheckOrder itemCheckOrder = new EamPointCheckOrder();
        itemCheckOrder.setLastUpdatedUserId(SecurityUtils.getUserId());
        itemCheckOrder.setLastUpdateTime(new Date());
        itemCheckOrder.setDeleted(1);

        QueryWrapper<EamPointCheckOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamPointCheckOrder::getPlanId, dto.getId());
        queryWrapper.lambda().eq(EamPointCheckOrder::getOrderStatus, 1);
        eamPointCheckOrderService.update(itemCheckOrder, queryWrapper);
//        eamPointCheckOrderService.remove(queryWrapper);

        QueryWrapper<EamAssetInfo> assetInfoQueryWrapper = new QueryWrapper<>();
        assetInfoQueryWrapper.lambda().eq(EamAssetInfo::getAssetCode, dto.getMouldCode());
        assetInfoQueryWrapper.lambda().eq(EamAssetInfo::getDeleted, 0);
        List<EamAssetInfo> eamAssetInfoList = eamAssetInfoService.list(assetInfoQueryWrapper);
        if (eamAssetInfoList.size() == 0) {
            return;
        }
        EamAssetInfo eamAssetInfo = eamAssetInfoList.get(0);
        //点检信息赋值
        for (EamPointCheckOrderDTO set : dto.getListCheckOrder()) {
            set.setPlanId(dto.getId());
            set.setAssetId(eamAssetInfo.getId());
            set.setAssetCode(eamAssetInfo.getAssetCode());
            set.setAssetName(eamAssetInfo.getAssetName());
            saveSpotCheck(set);
        }
    }

    public void saveSpotCheckIn(EamAssetInfoDTO dto, String planId) {
        if (dto.getListCheckOrder() == null) {
            return;
        }

        //点检信息赋值
        for (EamPointCheckOrderDTO set : dto.getListCheckOrder()) {
            set.setPlanId(planId);
            set.setAssetId(dto.getId());
            set.setAssetCode(dto.getAssetCode());
            set.setAssetName(dto.getAssetName());
            saveSpotCheck(set);
        }
    }
}
